<template>
  <el-dialog :visible.sync="isShow" width="600px" :show-close="false" class="register">
    <div class="title" slot="title">用户注册</div>
    <el-form :model="form" label-width="90px" :rules="rules" ref="form">
      <el-form-item label="头像" class="uploads_img" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl+'/uploads'"
          :show-file-list="false"
          name="image"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar" /> -->
          <img v-if="imageUrl" :src="baseUrl+'/'+imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item prop="username" label="昵称">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="手机">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-form-item prop="code" label="图形码">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <img @click="codeImgClick" class="codeImg" :src="baseUrl+codeUrl" alt />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item prop="rcode" label="验证码">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-button @click="RcodeClick" :disabled="time!=60">
              获取用户验证码
              <span v-if="time!=60">({{time}})</span>
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div class="footer" slot="footer">
      <el-button @click="isShow=false">取消</el-button>
      <el-button type="primary" @click="fn">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPhoneCode, goRegister } from "@/api/register.js";
export default {
  data() {
    return {
      time: 60,
      form: {
        avatar: "",
        username: "",
        email: "",
        phone: "",
        password: "",
        code: "",
        rcode: "",
      },
      rules: {
        avatar: [{ required: true, message: "请上传头像", trigger: "change" }],
        username: [
          { required: true, message: "请输入正确的昵称", trigger: "change" },
          { min: 2, max: 6, message: "请输入2-6位昵称" },
        ],
        email: [
          { required: true, message: "请输入正确的邮箱号", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请正确输入邮箱"));
              }
            },
            trigger: "change",
          },
        ],
        phone: [
          { required: true, message: "请输入正确的手机号", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确手机号"));
              }
            },
            trigger: "change",
          },
        ],
        password: [
          { required: true, message: "请输入正确的密码", trigger: "change" },
          { min: 6, max: 12, message: "请输入6-12位密码" },
        ],
        code: [
          { required: true, message: "请输入正确的图形码", trigger: "change" },
        ],
        rcode: [
          { required: true, message: "请输入正确的验证码", trigger: "change" },
        ],
      },
      isShow: false,
      baseUrl: process.env.VUE_APP_URL,
      codeUrl: "/captcha?type=sendsms",
      imageUrl: "",
    };
  },
  watch: {
    isShow(newVal) {
      if (newVal == false) {
        // 清空表单
        this.$refs.form.resetFields();
        // 将图片置空
        this.imageUrl = "";
      }
    },
  },
  methods: {
    handleAvatarSuccess(res) {
      //   this.imageUrl = URL.createObjectURL(file.raw);
      //   console.log(res);
      this.imageUrl = res.data.file_path;
      //人为触发表单验证(头像)
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField(["avatar"]);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    fn() {
      this.$refs.form.validate((result) => {
        if (result) {
          goRegister(this.form).then(() => {
            this.isShow = false;
            this.$message.success("注册成功");
          });
        } else {
          this.$message.error("注册失败");
        }
      });
    },
    //点击更换图形码
    codeImgClick() {
      this.codeUrl = "/captcha?type=sendsms&mmd=" + Date.now();
    },
    //获取短信验证码
    RcodeClick() {
      let num = 0;
      this.$refs.form.validateField(["phone", "code"], (err) => {
        if (err == "") {
          num++;
        }
      });
      if (num == 2) {
        this.time--;
        let a = setInterval(() => {
          this.time--;
          if (this.time == 0) {
            this.time = 60;
            clearInterval(a);
          }
        }, 1000);
        // this.$axios({
        //   url: "/sendsms",
        //   method: "post",
        //   data: {
        //     code: this.form.code,
        //     phone: this.form.phone,
        //   },
        // })
        getPhoneCode({
          code: this.form.code,
          phone: this.form.phone,
        }).then((res) => {
          console.log(res);
          this.$message.success(res.data.data.captcha + "");
        });
      } else {
        this.$message.error("请输入手机号与图形码");
      }
    },
  },
};
</script>

<style lang="less">
.register {
  .el-dialog__header {
    padding: 0;
  }
  .title {
    width: 100%;
    height: 53px;
    color: #ffffff;
    text-align: center;
    background: linear-gradient(#1493fa, #01c6fa);
    line-height: 53px;
    font-size: 14px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .uploads_img {
    text-align: center;
  }
  .codeImg {
    width: 100%;
    height: 40px;
  }
  .footer {
    text-align: center;
  }
}
</style>